﻿using System.Collections.Generic;
using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class FunctionCallParser
        : ExpressionParser
    {

        public FunctionCallParser()
        {
            ArgumentListParsers = new List<ExpressionParser>();
        }

        public override Expression Parse(Token[] tokens, int index)
        {
            if (index < tokens.Length - 2 && tokens[index].Type == TokenType.Identifier && tokens[index + 1].Type == TokenType.RoundOpen)
            {
                var function = new FunctionCall
                                   {
                                       Identifier = tokens[index],
                                       ArgumentList = ParseSubExpression(tokens, index + 1, 1, ArgumentListParsers),
                                       StringIndex = tokens[index].Index
                                   };
                function.Add(new SingleToken() { Token = function.Identifier});
                if (function.ArgumentList != null) function.Add(function.ArgumentList);
                function.TokenLength = 1 + function.ArgumentList.TokenLength;
                var semiColonIndex = index + 1 + function.ArgumentList.TokenLength;
                if (semiColonIndex < tokens.Length)
                {
                    var semiColon = tokens[semiColonIndex];
                    if (semiColon.Type == TokenType.SemiColon)
                    {
                        function.SemiColon = semiColon;
                        function.TokenLength++;
                        function.Add(new SingleToken() { Token = semiColon});
                    }
                }

                var lastToken = tokens[index + function.TokenLength - 1];
                function.StringLength = lastToken.Index + lastToken.Value.Length - function.StringIndex;


                return function;
            }
            return null;
        }

        public List<ExpressionParser> ArgumentListParsers { get; set; }

    }
}
